package com.controller;

import com.common.QiniuCloudUtil;
import com.common.Result;
import com.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * User的路由接口服务
 * 
 * @author 
 *
 */
@RestController
@RequestMapping("pcApi")
public class UploadController {

	/** UserService服务 */
	@Autowired
	private ArticleService articleService;

	/**
	 * 上传图片
	 * @param
	 * @return
	 */
	@ResponseBody
	@PostMapping(value = "/upload", produces = {"application/json;charset=UTF-8"})
	public Result upload(@RequestParam String base64,int dataNum){

		Result result = new Result();

		if (base64.isEmpty()) {
			result.setErrcode("400");
			result.setErrmsg("文件为空，请重新上传");
			return result;
		}

		String imageName = UUID.randomUUID().toString();

		QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
		try {
			//使用base64方式上传到七牛云
			String url = qiniuUtil.put64image(base64, imageName,dataNum);
			result.setErrcode("200");
			result.setErrmsg("文件上传成功");
			result.setUrl(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

	}

	@ResponseBody
	@PostMapping(value = "/uploadimg", produces = {"application/json;charset=UTF-8"})
	public Result uploadImg(@RequestParam("file") MultipartFile image) {
		Result result = new Result();
		if (image.isEmpty()) {
			result.setErrcode("400");
			result.setErrmsg("文件为空，请重新上传");
			return result;
		}

		try {
			byte[] bytes = image.getBytes();
			String imageName = UUID.randomUUID().toString();

			QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
			try {
				//使用base64方式上传到七牛云
				String url = qiniuUtil.put64image_(bytes, imageName);
				result.setErrcode("200");
				result.setErrmsg("文件上传成功");
				result.setUrl(url);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		} catch (IOException e) {
			result.setErrcode("500");
			result.setErrmsg("文件上传发生异常！");
			return result;
		}
	}




}
